package com.chengww.grab_rp.database.user

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import com.chengww.grab_rp.database.AppDatabase
import com.chengww.grab_rp.database.plugin.PluginDao
import com.chengww.grab_rp.database.plugin.PluginData
import com.chengww.grab_rp.database.plugin.PluginDataConstant

/**
 * Created by chengww on 2/20/21
 * @author chengww
 */
class UserDao private constructor(private val pluginDao: PluginDao) {

    fun isUerLoggedIn() = pluginDao.getData(PluginDataConstant.ID_USER) != null

    fun getUser(): User? = pluginDao.getData(PluginDataConstant.ID_USER)?.let {
        User(it.key1, it.key2, it.key3)
    }

    fun getUserLive(): LiveData<User?> = MediatorLiveData<User?>().also { user ->
        user.addSource(pluginDao.getDataLive(PluginDataConstant.ID_USER)) {
            user.value = it?.let {
                User(it.key1, it.key2, it.key3)
            }
        }
    }

    fun insert(user: User) {
        pluginDao.insert(
            PluginData(
                user.md5Key, user.plugId, user.token, PluginDataConstant.ID_USER
            )
        )
    }

    fun delete() {
        pluginDao.delete(PluginDataConstant.ID_USER)
    }

    companion object {
        private var INSTANCE: UserDao? = null

        fun getInstance(context: Context) =
            INSTANCE ?: UserDao(AppDatabase.getInstance(context).pluginDao())
    }
}